package crypt

import (
	"fmt"
	"fx_swift_agent/pkg/utils"
	"golang.org/x/crypto/bcrypt"
)

// HashPassword hashes the given password using bcrypt.
func HashPassword(password string) (hashedPassword, salt string, err error) {
	saltBytes := []byte(utils.RandStringBytesMaskImprSrc(5))
	saltedPass := append(saltBytes, []byte(password)...)
	hashedPasswordBytes, err := bcrypt.GenerateFromPassword(saltedPass, bcrypt.DefaultCost)
	if err != nil {
		return "", "", fmt.Errorf("error hashing password: %w", err)
	}

	return string(hashedPasswordBytes), string(saltBytes), nil
}

// ComparePassword compares the given password with the given hash.
func ComparePassword(hashedPassword, salt, password string) error {
	saltedPass := append([]byte(salt), []byte(password)...)
	return bcrypt.CompareHashAndPassword([]byte(hashedPassword), saltedPass)
}
